import { View, Image, Video } from "@tarojs/components";
import { Uploader } from '@antmjs/vantui'
import uploadIcon from '@/assets/images/upload-icon.png'
import { useEffect } from "react";
import './photoVideo.scss'
import { handleCleanStore, handleInitStoreBaseInfo, handleLoginCallback, showToast } from "@/common/util";
import Taro from "@tarojs/taro";
import { handleShopUserprofileAdd } from "@/common/service";
import useInitAction from "@/hooks/useInitAction";
import useUploadPhotoAction from "@/hooks/useUploadPhotoAction";
import useUpladVideoAction from "@/hooks/useUpladVideoAction";
import { PAGE_PATH, RESPONSE_CODE, STORE_KEY } from "@/common/config";
import { API_URL } from "@/common/serviveApi";
import { USER_PROFILE_STATUS } from "@/typing";
// import useSeviceTypeAction from "@/hooks/useSeviceTypeAction";
import finishBg from '@/assets/images/finish-bg.png'

import playIcon from '@/assets/images/play.png'

const PhotoVideo: React.FC = () => {
    // const { handleInitSubmitServiceTypeInfo } = useSeviceTypeAction()

    const { photoList, setPhotoList, handleBeforeUploadPhoto, handleFormatPhotoList, handleInitStorePhotoList, handleAfterUploadPhoto, handleDeletePhotoAction } = useUploadPhotoAction()
    const { videoPoster,
        videoUrl,
        playStatus, setPlayStatus,
        handleDeleteVideo,
        handleAfterUploadVideo,
        handleBeforeUploadVideo,
        setVideoUrl } = useUpladVideoAction();

    const { bottomSafeHeight } = useInitAction()
    const handleInit = () => {
        const videoUrl = Taro.getStorageSync(STORE_KEY.VIDEO_URL)
        const userProfileStatus = Taro.getStorageSync(STORE_KEY.USER_PROFILE_STATUS)
        const storePhotoList = handleInitStorePhotoList() || []
        let storePhotoListT = []
        if (storePhotoList.length > 0) {
            if (userProfileStatus === USER_PROFILE_STATUS.unknown) {
                storePhotoListT = storePhotoList.map((photo) => {
                    const thumb = photo.thumb ? photo.thumb : photo
                    const url = photo.url ? photo.url : photo
                    return {
                        ...photo,
                        thumb: `${API_URL}${thumb}`,
                        url: `${API_URL}${url}`,
                    }
                });
            } else {
                storePhotoListT = handleFormatPhotoList(storePhotoList)
            }
        }

        setPhotoList(storePhotoListT)

        if (videoUrl) {

            setVideoUrl(videoUrl)
        }
    }

    const handleSubmit = async () => {
        if (videoUrl === '' && photoList.length === 0) {
            showToast('请上传视频或者图片')


            return
        }
        const storeBaseUserInfo = handleInitStoreBaseInfo();
        const storeTopicList = JSON.parse(Taro.getStorageSync(STORE_KEY.TOPIC))
        const userReadMe = Taro.getStorageSync(STORE_KEY.README);
        const storeJobIdList = JSON.parse(Taro.getStorageSync(STORE_KEY.JOB_ID_LIST))
        const storeServiceTypeIdList = JSON.parse(Taro.getStorageSync(STORE_KEY.ADD_SERVICE_TYPE))
        const storePhotoList = handleInitStorePhotoList()
        const computedPhotoObj = {}
        const computedTopObj = {}
        const computedJobObj = {}
        const computedServiceObj = {}
        const storeUserProfileStatus = Taro.getStorageSync(STORE_KEY.USER_PROFILE_STATUS) || USER_PROFILE_STATUS.unknown;
        storePhotoList.forEach((photo, index) => {
            const keyVal = `media_img[${[index]}]`
            computedPhotoObj[keyVal] = photo
        })

        storeJobIdList.forEach((id, index) => {

            const keyIdVal = `job_type_id[${[index]}]`
            computedJobObj[keyIdVal] = id


        })
        storeTopicList.forEach((topic, index) => {
            const keyVal = `topic[${[index]}][title]`
            if (storeUserProfileStatus === USER_PROFILE_STATUS.disable) {
                const keyIdVal = `topic[${[index]}][id]`
                computedTopObj[keyIdVal] = topic['id']
            }
            computedTopObj[keyVal] = topic['title']
        })
        storeServiceTypeIdList.forEach((typeId, index) => {

            const keyIdVal = `service_type_id[${[index]}]`
            computedServiceObj[keyIdVal] = typeId


        })
        const videoStartIndex = videoUrl.indexOf('/storage');
        const videoPath = videoUrl.substring(videoStartIndex);
        const avatarPath = storeBaseUserInfo['avatar'].substring(videoStartIndex);
        storeBaseUserInfo['avatar'] = avatarPath;
        const submitInfo = {
            ...storeBaseUserInfo,
            readme: userReadMe,
            media_video: videoPath,
            ...computedJobObj,
            ...computedServiceObj,
            ...computedPhotoObj,
            ...computedTopObj
        }

        console.log(submitInfo)
        // return
        Taro.showLoading({
            title: '提交中...',
            mask: true,
        })
        let submitRes = await handleShopUserprofileAdd(submitInfo) as any
        Taro.hideLoading({

        })
        if (submitRes.statusCode === RESPONSE_CODE.AJAX_SUCCESS) {
            const submitResult = submitRes.data;
            if (submitResult.code === RESPONSE_CODE.SUCCESS) {
                showToast(submitResult.msg)


                handleCleanStore();
                Taro.reLaunch({
                    url: `${PAGE_PATH.EXAMINE_PROCESS}?pageEntry=2`
                })


            } else if (submitResult.code === RESPONSE_CODE.LOGIN_EXPIRE || submitResult.code === RESPONSE_CODE.LOGIN_NEED) {
             
                handleLoginCallback(async () => {
                    submitRes = await handleShopUserprofileAdd(submitInfo);
                })
               

            } else {
                showToast(submitResult.msg)

            }

        } else {
            showToast('服务器错误')

        }

    }
    useEffect(() => {

        handleInit()

    }, [])

    useEffect(() => {
        if (videoUrl === '' || photoList.length === 0) {

        } else {

        }
    }, [videoUrl, photoList])
    return <>
        <View className="min-h-100vh bg-#F6F6F6 box-border pt-68px w-750px overflow-x-hidden">
            <View style={{ paddingBottom: bottomSafeHeight > 0 ? bottomSafeHeight + 70 + 'px' : '160rpx' }}>
                <View className="box-border  pl-72px text-#161618 text-28px font-bold ">请上传一段视频或几张照片，将展示在个人主页</View>
                <View className="pl-60px pr-58px box-border pt-54px flex flex-col items-center">
                    {videoUrl != '' ? <View className="w-364px h-544px relative">
                        <Video
                            id='video'
                            className="w-364px h-544px relative "
                            onTap={() => setPlayStatus(!playStatus)}
                            src={`${API_URL}${videoUrl}`}
                            poster={videoPoster}
                            initialTime={0}

                            autoplay={false}
                            loop={false}
                            muted={false}
                            onEnded={() => setPlayStatus(false)}
                        >
                            {!playStatus && <View className='video-controls'>
                                  <Image className='w-84px h-84px' src={playIcon} />
                                </View>}
                        </Video>
                        <View className="w-98px h-46px flex items-center justify-center bg-#1F1F1F text-#fff text-24px absolute bottom-0 right-0" onClick={handleDeleteVideo}>删除</View>
                    </View> :
                        <Uploader accept="video" compressed maxCount={1} onAfterRead={handleAfterUploadVideo} useBeforeRead onBeforeRead={handleBeforeUploadVideo} >
                            <View className="w-631px box-border bg-#fff flex flex-col items-center justify-center h-364px">
                                <Image src={uploadIcon} className="w-58px h-60px" />
                                <View className="mt-18px text-#666666 text-28px">视频</View>
                            </View>
                        </Uploader>

                    }


                    <View className="px-22px text-24px text-#999 mt-24px leading-34px ">3分钟以内，须有本人出镜及声音，可以是自我介绍或话题推荐类内容。</View>
                </View>

                <View className="box-border pt-38px" style={{ paddingLeft: photoList.length > 0 ? '40rpx' : '60rpx', paddingRight: photoList.length > 0 ? '30rpx' : '58rpx' }}>
                    <Uploader accept='image' multiple={true} maxCount={9} fileList={photoList} onBeforeRead={handleBeforeUploadPhoto} onAfterRead={handleAfterUploadPhoto} onDelete={handleDeletePhotoAction}>
                        <View className=" box-border bg-#fff flex flex-col items-center justify-center" style={{ width: photoList.length > 0 ? '208rpx' : '631rpx', height: photoList.length > 0 ? '306rpx' : '364rpx' }}>
                            <Image src={uploadIcon} className="w-58px h-60px" />
                            <View className="mt-18px text-#666666 text-28px">照片</View>
                        </View>
                    </Uploader>
                    <View className="px-22px text-24px text-#999 mt-24px leading-34px text-center w-full">最多可传9张。</View>
                </View>
            </View>
            <View className="fixed bg-#fff left-0 bottom-0 right-0 pt-20px z-10 flex items-center justify-center " style={{ paddingBottom: bottomSafeHeight > 0 ? bottomSafeHeight + 'px' : '50rpx' }}>

                <View className=" w-400px h-108px box-border flex items-center justify-center text-36px text-#333" style={{ backgroundImage: `url(${finishBg})`, backgroundRepeat: 'no-repeat', backgroundSize: '100% 100%' }} onClick={handleSubmit}>完成，提交审核</View>
            </View>


        </View>
    </>
}
export default PhotoVideo;